<?php

namespace app\admin\controller;

use app\common\controller\Agent;
use app\common\controller\Backend;
use app\common\library\Log;
use app\common\model\AgentMoneyRecord;
use app\common\model\AgentWithdrawalRecord;
use app\common\model\Bank;
use app\common\model\Images;
use app\common\model\Member;
use app\common\model\Order;
use app\common\model\OrderAftersalesRecord;
use app\common\model\PlatformMoneyRecord;
use EasyWeChat\Factory;
use think\Db;
use think\Env;
use think\Exception;
use think\Queue;
use Wxcrypt\XcxPay;

/**
 * 资金明细
 *
 * @icon fa fa-user
 */
class WithdrawalRecord extends Backend
{

    protected $relationSearch = true;
    protected $multiFields = 'status';

    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('AgentWithdrawalRecord');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            $list = $this->model->with(['bank','agent'])->where($where)->order($sort, $order)->paginate($limit)->each(function ($item){
                if (!empty($item['fail_reason'])){
                    $item['fail_reason'] = config('err_code')[$item['fail_reason']];
                }
                return $item;
            });;

            if (empty($filter['status'])) { //全统计
                $money_amount = $this->model->with(['bank','agent'])->where($where)->sum('agent_withdrawal_record.money');//总提现金额
                $wait_amount = $this->model->with(['bank','agent'])->where($where)->where('agent_withdrawal_record.status',1)->sum('agent_withdrawal_record.money');//待审核总额
                $success_amount = $this->model->with(['bank','agent'])->where($where)->where('agent_withdrawal_record.status',2)->sum('agent_withdrawal_record.money');//审核成功总额
                $fail_amount = $this->model->with(['bank','agent'])->where($where)->where('agent_withdrawal_record.status',3)->sum('agent_withdrawal_record.money');//审核失败总额
            }elseif ($filter['status'] == 1){
                $money_amount = $this->model->with(['bank','agent'])->where($where)->where('agent_withdrawal_record.status',1)->sum('agent_withdrawal_record.money');//总提现金额
                $wait_amount = $money_amount;
                $success_amount = 0;
                $fail_amount = 0;
            }elseif ($filter['status'] == 2){
                $money_amount = $this->model->with(['bank','agent'])->where($where)->where('agent_withdrawal_record.status',2)->sum('agent_withdrawal_record.money');//总提现金额
                $wait_amount = 0;
                $money_amount = $money_amount;
                $success_amount = 0;
                $fail_amount = 0;
            }elseif ($filter['status'] == 3){
                $money_amount = $this->model->with(['bank','agent'])->where($where)->where('agent_withdrawal_record.status',3)->sum('agent_withdrawal_record.money');//总提现金额
                $wait_amount = 0;
                $success_amount = 0;
                $fail_amount = $money_amount;
            }
            $count = [['name'=>'总提现金额','value'=>sprintf("%.3f",$money_amount)],['name'=>'审核失败总额','value'=>sprintf("%.3f",$fail_amount)],['name'=>'审核成功总额','value'=>sprintf("%.3f",$success_amount)],['name'=>'待审核总额','value'=>sprintf("%.3f",$wait_amount)]];
            $result = array("total" => $list->total(), "rows" => $list->items(),'extend'=>['count'=>$count]);
            return json($result);
        }
        return $this->view->fetch();
    }

    public function pass($ids=null)
    {
        Db::startTrans();
        try{
            if (empty($ids)){
                throw new Exception('参数ID缺失');
            }
            $info = AgentWithdrawalRecord::get(['id'=>$ids,'status'=>1]);
            if (empty($info)){
                throw new Exception('该条提现记录信息不存在');
            }
            $agent_info = \app\common\model\Agent::get($info['agent_id']);
            if ($info['method'] == 2) { //提现到微信余额
                //获取代理商openid
                if (empty($agent_info['member_id']))
                    throw new Exception('该代理未绑定微信用户信息');
                $member_info = Member::get($agent_info['member_id']);
                // 发起微信转账申请
                $xccPay = new XcxPay();
                $result = $xccPay->transfer_batches($member_info['mini_openid'],$info['money']);
                if (isset($result['code']))
                    throw new Exception('申请微信支付失败：'.$result['message']);
                $info->batch_id = $result['batch_id'];
                $info->out_batch_no = $result['out_batch_no'];
                $info->status = 4;
                $info->save();
            }else{
                //平台收益记录
                PlatformMoneyRecord::create(['type'=>2,'detail_type'=>PlatformMoneyRecord::DETAIL_TYPE_AGENT_TX,'money'=>$info['money'],'remark'=>$info['id'],'createtime'=>time()]);
                $info->status = 2;
                $info->save();
                if (!empty($agent_info) && !empty($agent_info['member_id'])){
                    $bank_name = Bank::where('id',$info['bank_id'])->value('bank_name');
                    Queue::push(\app\job\Message::class,[
                        'member_id'=>$agent_info['member_id'],
                        'template_id'=>config('wechat_gzh')['gzh_template']['tixian_success'],
                        'data'=>[
                            'time3'=>$info['createtime'],
                            'character_string2'=>$info['id'],
                            'thing4'=>$info['method'] == 2 ? '微信零钱' : $bank_name.'('.substr($info['account'],-4).')',
                            'amount5'=>$info['money'],
                            'thing7'=>"本人"
                        ]
                    ],'message');
                }
            }
            Db::commit();
            $this->success();
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    public function refuse($ids=null)
    {
        Db::startTrans();
        try{
            if (empty($ids)){
                throw new Exception('参数ID缺失');
            }
            $info = AgentWithdrawalRecord::get(['id'=>$ids,'status'=>1]);
            if (empty($info)){
                throw new Exception('该条提现记录信息不存在');
            }
            $agent = \app\common\model\Agent::get($info->agent_id);
            //退回余额
            $balance = bcadd($agent->money,$info->money,2);
            $agent->money = $balance;
            $agent->save();
            //退回记录
            AgentMoneyRecord::create(['type'=>4,'money'=>$info->money,'balance'=>$balance,'agent_id'=>$agent->id]);
            $info->status = 3;
            $info->save();
            Db::commit();
            Queue::push(\app\job\Message::class,[
                'member_id'=>$agent['member_id'],
                'template_id'=>config('wechat_gzh')['gzh_template']['tixian_audit'],
                'data'=>[
                    'time1'=>date('Y-m-d'),
                    'amount2'=>$info->money,
                    'thing3'=>'提现审核失败'
                ]
            ],'message');
            $this->success();
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
    }



}
